﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebControls;
using DecodingSharePoint.SharePoint;
using Microsoft.SharePoint;

namespace DecodingSharePoint_Regex_Field.CONTROLTEMPLATES
{
    public partial class DS_Regex_FieldEditor : UserControl, IFieldEditor
    {
        private DS_Regex_Field fldParentField;

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public void InitializeWithField(SPField field)
        {
            this.fldParentField = field as DS_Regex_Field;

            if (this.Page.IsPostBack)
            {
                return;
            }

            //when modifying a field check the correct radio button
            if (field != null)
            {
                string regularExpressionType = fldParentField.RegexType;
                string otherRegularExpression = fldParentField.OtherRegex;
                string errorMessage = fldParentField.ErrorMessage;
                txtOtherRegex.Text = otherRegularExpression;
                rbnRegexType.SelectedValue = regularExpressionType;
                txtErrorMessage.Text = errorMessage;

                EnableDisableControls(regularExpressionType);
            }
        }
        
        public void OnSaveChange(SPField field, bool bNewField)
        {
            DS_Regex_Field parentField = (DS_Regex_Field)field;

            parentField.IsNew = bNewField;

            parentField.RegexType = rbnRegexType.SelectedValue;
            if (parentField.RegexType == DS_Regex_Common.RegexType.Other)
            {
                parentField.OtherRegex = txtOtherRegex.Text;
                parentField.ErrorMessage = txtErrorMessage.Text;
            }
        }

        // Properties
        public bool DisplayAsNewSection
        {
            get
            {
                return false;
            }
        }

        protected void rbnRegexType_SelectedIndexChanged(object sender, EventArgs e)
        {
            EnableDisableControls(rbnRegexType.SelectedValue);
        }
        
        private void EnableDisableControls(string regularExpressionType)
        {
            if (regularExpressionType == DS_Regex_Common.RegexType.Other)
            {
                txtOtherRegex.Visible = true;
                txtErrorMessage.Visible = true;
                lblErrorMessage.Visible = true;
                lblOtherRegex.Visible = true;
            }
            else
            {
                txtErrorMessage.Text = string.Empty;
                txtOtherRegex.Text = string.Empty; 
                txtOtherRegex.Visible = false;
                txtErrorMessage.Visible = false;
                lblErrorMessage.Visible = false;
                lblOtherRegex.Visible = false;
            }
        }       
    }
}
